
#include "rallypoint.h"
#include "gamemanager.h"
#include "resourcemanager.h"

#define __super		Tower

int Flag::COLOR_SEED = 0;

Flag::Flag( const Point& pos ) : __super(pos)
{
	color = (FlagColor)COLOR_SEED;
	COLOR_SEED++;

	type = TowerType::rally_point;

	memset(soldierPositionFlags, 0, SOLDIERS_PER_FLAG);

	static const int arr[] = {0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330};
	
	int distance = 25 + rand() % 25;
	int indexes[SOLDIERS_PER_FLAG];
	for(int i = 0; i < SOLDIERS_PER_FLAG; ++i) {
		bool found = false;
		do {
			indexes[i] = rand() % 12;
			found = false;
			for(int j = 0; j < i; ++j) {
				if(i == j) {
					continue;
				}

				if(indexes[i] == indexes[j]) {
					found = true;
					break;
				}
			}
		} while(found);
	}
	
	for(int i = 0; i < SOLDIERS_PER_FLAG; ++i) {
		Point pt = Point(distance, 0.0f).rotateByAngle(Point::ZERO, arr[indexes[i]] * (M_PI / 180));
		soldierPositions[i] = pt;
	}
}

Flag::~Flag()
{

}

void Flag::init()
{
	static const char* FLAG_COLOR_NAMES[] = {
		"textures/entities/blue_flag.png",
		"textures/entities/green_flag.png",
		"textures/entities/orange_flag.png",
		"textures/entities/purple_flag.png",
		"textures/entities/red_flag.png",
		"textures/entities/skyblue_flag.png",
		"textures/entities/yellow_flag.png",

	};

	sprite = CREATE_SPRITE(FLAG_COLOR_NAMES[(int)color]);
	sprite->setAnchorPoint(Point(0.5f, 0.0f));
	sprite->setPosition(position);
}

bool Flag::update( float ticks )
{
	return true;
}

int Flag::getSoldierPositionIndex()
{
	int ret = -1;

	for(int i = 0; i < SOLDIERS_PER_FLAG; ++i) {
		if(!soldierPositionFlags[i]) {
			ret = i;
			soldierPositionFlags[i] = true;
			break;
		}
	}

	return ret;
}

void Flag::onSoldierDied( int positionIndex )
{
	soldierPositionFlags[positionIndex] = false;

	bool haveSoldiers = false;
	for(int i = 0; i < SOLDIERS_PER_FLAG; ++i) {
		if(soldierPositionFlags[i]) {
			haveSoldiers = true;
			break;
		}
	}

	if(!haveSoldiers) {
		// update display
	}
}
